import { createAction } from 'redux-actions'
import { UPDATEUSERINFO } from '../types/userinfo'
import { loginRequest } from '../../service/login-controller'
import { showToast } from '../../crossplatform/apiservice/toast'
import { navigateBack, navigateTo, redirectTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import {
  changeMobileRequest,
  createAccountRequest,
  getZhichuUserInfoBByAuth,
  getZhichuUserInfoByAuth,
  editUserInfoRequest
} from '../../service/user-info-controller'
import { ownerCompany } from '../../service/org-company-controller'
import { getStorageSync } from '../../crossplatform/apiservice/storage'
import judgeBlack from '../../util/judge_black'

// 根据auth userId拿职初C信息
export const getZhichuUserInfo = createAction(UPDATEUSERINFO, ({ userId }) => {
  return new Promise(resolve => {
    getZhichuUserInfoByAuth({ userId }).then(({ data }) => {
      const { entry } = data
      if (entry && Object.keys(entry).length > 0) {
        resolve({
          userId: userId,
          zhichuUserId: entry.id,
          mobile: entry.mobile,
          userInfoC: {
            mobile: entry.mobile,
            gender: entry.gender,
            gmtBirth: entry.gmtBorth ? entry.gmtBorth.substring(0, 4) : '',
            userAvator: entry.userAvator,
            userName: entry.userName
          }
        })
      } else {
        resolve({})
      }
    })
  })
})

// 根据auth userId拿职初B信息
export const getZhichuBUserInfo = createAction(UPDATEUSERINFO, ({ userId }) => {
  return new Promise(resolve => {
    getZhichuUserInfoBByAuth({ userId }).then(({ data }) => {
      const { entry, message } = data
      let payloaddata = {}
      const yearPre18 = new Date().getFullYear() - 18
      if (entry) {
        payloaddata = {
          userId: userId,
          zhichuUserIdB: userId,
          // role: entry.role === 0 ? 'personal' : 'company',
          mobile: entry.mobile,
          userInfoB: {
            userName: entry.userName,
            userAvator: entry.userAvator,
            mobile: entry.mobile,
            position: entry.postion,
            sex: entry.gender || '1',
            birthday: entry.birthday || yearPre18
          }
        }
      } else {
        payloaddata = {}
      }
      ownerCompany().then(({ data }) => {
        let datacp = data && data.entry
        let datastatus = data && data.status
        if (datacp && datacp.length && datastatus) {
          const datacpsingle = datacp[0]
          resolve({
            ...payloaddata,
            companyId: datacpsingle && datacpsingle.companyId,
            companyName: datacpsingle && datacpsingle.companyName
          })
        } else {
          resolve({
            ...payloaddata
          })
        }
      })
    })
  })
})

export const updateCompanyId = createAction(UPDATEUSERINFO, () => {
  return new Promise(resolve => {
    ownerCompany().then(({ data }) => {
      const userinfo = getStorageSync('userinfo') || {}
      const { companyId, companyName, companyLogo, master } = userinfo

      let datacp = data && data.entry
      let datastatus = data && data.status
      if (companyId) {
        judgeBlack.getBlackCompanyIds(companyId)
        resolve({
          master: master || true,
          companyId: companyId,
          companyName: companyName || '',
          companyLogo: companyLogo || ''
        })
      } else {
        if (datacp && datacp.length && datastatus) {
          const datacpsingle = datacp[0]
          judgeBlack.getBlackCompanyIds(datacpsingle && datacpsingle.companyId)
          resolve({
            master: datacpsingle.master || true,
            companyId: datacpsingle && datacpsingle.companyId,
            companyName: datacpsingle && datacpsingle.companyName,
            companyLogo: datacpsingle && datacpsingle.companyLogo
          })
        } else {
          resolve({
            companyId: '',
            companyName: '',
            companyLogo: '',
            master: false
          })
        }
      }
    })
  })
})

// 获取auth userId
export const queryUserId = createAction(UPDATEUSERINFO, ({ mobile, code, type, identifier, detailIn, roleType }) => {
  return new Promise(resolve => {
    loginRequest({ mobile, code, type, identifier }).then(({ data }) => {
      const { code: returnCode, data: datain, message } = data
      if (returnCode === 200) {
        resolve({ userId: datain.userId, mobile: datain.mobile })
        redirectTo({
          url: `${pagejumplist['base-information'].path}${detailIn ? `?detailIn=${detailIn}` : ''}${roleType ? `?type=${roleType}` : ''}`
        })
      } else {
        showToast({
          title: message || '登录失败！'
        })
        resolve({})
      }
    })
  })
})

export const changeMobile = createAction(UPDATEUSERINFO, ({ identifier, type, mobile, code, isLogin }) => {
  return new Promise(resolve => {
    changeMobileRequest({ identifier, type, mobile, code }).then(({ data }) => {
      const { code: returnCode, message } = data
      if (returnCode === 200) {
        resolve({ mobile })
        if (isLogin) {
          // 如果是登录 , 走登录逻辑
          navigateTo({
            url: `${pagejumplist['self-message'].path}`
          })
        } else {
          // 如果是修改手机号
          navigateBack()
        }
      } else {
        showToast({
          title: message || '该手机号已被占用！'
        })
        resolve({})
      }
    })
  })
})

const formatdata = entry => {
  return {
    zhichuUserId: entry.userId
  }
}

export const upDateUserInfo = createAction(UPDATEUSERINFO, payload => {
  return new Promise(resolve => {
    createAccountRequest({ ...payload }).then(({ data }) => {
      const { networkerror, entry, status, message } = data
      if (networkerror) {
        resolve({
          networkerror: true
        })
      } else {
        if (status && entry) {
          let dataformat = formatdata(entry)
          resolve({
            networkerror: false,
            showEmpty: false,
            ...dataformat
          })
          navigateBack()
        } else {
          showToast({
            title: message || '请完善信息后提交'
          })
          resolve({
            networkerror: false,
            showEmpty: true
          })
        }
      }
    })
  })
})

export const editUserInfo = createAction(UPDATEUSERINFO, payload => {
  return new Promise(resolve => {
    editUserInfoRequest({ ...payload }).then(({ data }) => {
      const { status, message } = data
      resolve({
        status,
        message
      })
    })
  })
})
